import React, { useRef, useState } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import api from '../../services/api';
import { User } from '../../types';

const UserList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const { t, i18n } = useTranslation();

  const fetchUsers = async (params: any) => {
    try {
      const response = await api.get('/users/', {
        params: {
          skip: (params.current - 1) * params.pageSize,
          limit: params.pageSize,
        },
      });
      // Handle both array and paginated response
      const usersData = Array.isArray(response.data) ? response.data : response.data.items || [];
      const total = Array.isArray(response.data) ? response.data.length : response.data.total || 0;
      return {
        data: usersData,
        success: true,
        total: total,
      };
    } catch (error: any) {
      message.error(t('messages.loadFailed'));
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleDelete = async (id: number) => {
    setLoading(true);
    try {
      await api.delete(`/users/${id}`);
      message.success(t('messages.deleteSuccess'));
      actionRef.current?.reload();
    } catch (error: any) {
      message.error(error.response?.data?.detail || t('messages.deleteFailed'));
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<User>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: t('user.username'),
      dataIndex: 'username',
      copyable: true,
    },
    {
      title: t('user.email'),
      dataIndex: 'email',
      copyable: true,
    },
    {
      title: t('user.role'),
      dataIndex: 'roles',
      render: (_, record) => {
        const roleColors: Record<string, string> = {
          'AppUser': 'default',
          'PlatformUser': 'blue',
          'Administrator': 'red',
          'SystemAdministrator': 'purple',
        };

        // Handle roles - convert from string or array to string array
        const getRolesArray = (roles: any): string[] => {
          if (!roles) return [];
          if (Array.isArray(roles)) return roles;
          if (typeof roles === 'string') return roles.split(',').filter((r: string) => r.trim());
          return [];
        };

        const roles = getRolesArray(record.roles);

        return (
          <>
            {roles.map(role => (
              <Tag key={role} color={roleColors[role] || 'default'}>
                {t(`user.roles.${role}`)}
              </Tag>
            ))}
          </>
        );
      },
      valueEnum: {
        AppUser: { text: t('user.roles.appUser'), status: 'Default' },
        PlatformUser: { text: t('user.roles.platformUser'), status: 'Processing' },
        Administrator: { text: t('user.roles.administrator'), status: 'Error' },
        SystemAdministrator: { text: t('user.roles.systemAdministrator'), status: 'Warning' },
      },
    },
    {
      title: t('user.createdAt'),
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: t('common.actions'),
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          icon={<EditOutlined />}
          onClick={() => navigate(`/users/edit/${record.id}`)}
        >
          {t('common.edit')}
        </Button>,
        <Popconfirm
          key="delete"
          title={t('user.deleteConfirm')}
          onConfirm={() => handleDelete(record.id)}
          okText={t('common.yes')}
          cancelText={t('common.no')}
        >
          <Button type="link" danger icon={<DeleteOutlined />} loading={loading}>
            {t('common.delete')}
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<User>
      columns={columns}
      actionRef={actionRef}
      request={fetchUsers}
      rowKey="id"
      search={{
        labelWidth: 'auto',
        searchText: t('table.search'),
        resetText: t('table.reset'),
      }}
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: true,
        showTotal: (total, range) =>
          i18n.language === 'zh'
            ? `显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            : `Showing ${range[0]}-${range[1]} of ${total} items`,
      }}
      dateFormatter="string"
      headerTitle={t('user.title')}
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => navigate('/users/create')}
          type="primary"
        >
          {t('user.create')}
        </Button>,
      ]}
    />
  );
};

export default UserList;
